<script setup>
import { ref, defineEmits } from 'vue'
import { useUserStore } from '@/stores'

import {
  Delete,
  Edit,
  Plus,
  Unlock,
  Search,
  RefreshRight
} from '@element-plus/icons-vue'
import {
  queryUserListApi,
  getUserInfoApi,
  updateUserInfoApi,
  addAdminApi,
  updateLockedApi,
  deleteAdminApi
} from '@/apis/admin-user'
const userStore = useUserStore()

const emit = defineEmits(['title'])
emit('title', '员工管理')
const defaultForm = {
  id: null,
  username: '',
  password: '',
  nickName: '',
  phone: '',
  gender: null
}
const params = ref({
  pageNo: 1,
  pageSize: 10,
  username: '',
  gender: null
})

// 搜索
const onSearch = async () => {
  params.value.pageNo = 1
  getUserList()
}

const onReset = () => {
  params.value = {
    pageNo: 1,
    pageSize: 10,
    username: '',
    gender: null
  }
  getUserList()
}

const tableData = ref([])
const columns = [
  {
    prop: '',
    type: 'selection'
  },
  {
    prop: '',
    type: 'index',
    label: '序号',
    width: 80
  },
  {
    prop: 'username',
    label: '用户名',
    width: 100,
    type: 'text'
  },
  {
    prop: 'nickName',
    label: '昵称',
    width: 120,
    type: 'text'
  },
  {
    prop: 'phone',
    label: '手机号',
    width: 120,
    type: 'text'
  },
  {
    prop: 'gender',
    label: '性别',
    type: 'enum',
    width: 100,
    enum: [
      {
        value: 1,
        label: '男'
      },
      {
        value: 2,
        label: '女'
      }
    ]
  },
  {
    prop: 'locked',
    label: '状态',
    type: 'enum',
    enum: [
      {
        value: 0,
        label: '正常',
        color: 'green'
      },
      {
        value: 1,
        label: '锁定',
        color: 'red'
      }
    ]
  },
  {
    prop: 'createTime',
    label: '创建时间',
    type: 'date',
    width: 150
  },
  {
    prop: '',
    type: 'operate',
    label: '操作',
    width: 300
  }
]
const total = ref(0)

// 获取数据
const getUserList = async () => {
  const res = await queryUserListApi(params.value)
  tableData.value = res.data.data.list
  tableData.value = tableData.value.filter(
    (item) => item.id !== userStore.userInfo.id
  )
  total.value = res.data.data.total
}

getUserList()

// 切换页大小
const sizeChange = (pageSize) => {
  params.value.pageNo = 1
  params.value.pageSize = pageSize
  getUserList()
}
// 切换页码
const currentChange = (e) => {
  params.value.pageNo = e
  getUserList()
}

const dialogVisible = ref(false)
const formData = ref({
  id: null,
  username: '',
  nickName: '',
  phone: '',

  gender: 1
})

const formRef = ref()
const formRules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名需要 4 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 20, message: '密码需要 6 到 20 个字符', trigger: 'blur' }
  ],
  nickName: [
    { required: true, message: '昵称不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称需要 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '手机号码不能为空', trigger: 'blur' },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: '手机号码格式不正确',
      trigger: 'blur'
    }
  ],
  gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }]
}

// 选择性别
const selectGender = (e) => {
  formData.value.gender = e
}

// open 打开弹窗
const open = async (id) => {
  // 清空表单中的提示信息
  if (formRef.value) {
    formRef.value.clearValidate()
  }
  if (id) {
    console.log('修改')
    const res = await getUserInfoApi(id)
    formData.value = res.data.data
  } else {
    console.log('新增')
    formData.value = { ...defaultForm }
  }
  dialogVisible.value = true
}

// 提交修改表单
const onSubmit = async () => {
  await formRef.value.validate()
  if (!formData.value.id) {
    // 新增

    await addAdminApi({
      username: formData.value.username,
      password: formData.value.password,
      nickName: formData.value.nickName,
      phone: formData.value.phone,
      gender: formData.value.gender
    })
  } else {
    // 修改
    await updateUserInfoApi({
      id: formData.value.id,
      nickName: formData.value.nickName,
      phone: formData.value.phone,
      gender: formData.value.gender
    })
  }

  ElMessage({
    message: formData.value.id ? '修改成功' : '新增成功',
    type: 'success'
  })
  dialogVisible.value = false
  getUserList()
}

const onLocked = async (row) => {
  if (row) {
    await updateLockedApi(row.id)
    ElMessage({
      message: row.locked === 1 ? '禁用成功' : '启用成功',
      type: 'success'
    })
    getUserList()
  }
}
const ids = ref([])
// 多选删除
const handleSelectionChange = (e) => {
  ids.value = e
}

const onDelete = async (id) => {
  if (id) {
    await deleteAdminApi([id])
  } else {
    if (ids.value.length <= 0) {
      ElMessage({
        message: '请选择要删除的数据',
        type: 'warning'
      })
      return
    }

    await ElMessageBox.confirm('确定删除吗？', '温馨提示', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteAdminApi(ids.value)
  }
  ElMessage({
    message: '删除成功',
    type: 'success'
  })
  params.value.pageNo = 1
  getUserList()
}
</script>

<template>
  <div class="page">
    <TabComponent
      :tableData="tableData"
      :columns="columns"
      @selectionChange="handleSelectionChange"
      :height="440"
    >
      <template #header>
        <div class="search-box">
          <el-form :inline="true" :model="params" class="search-form">
            <el-form-item label="用户名">
              <el-input
                style="width: 13rem"
                v-model="params.username"
                placeholder="请输入用户名"
                clearable
              />
            </el-form-item>

            <el-form-item label="性别">
              <el-select
                v-model="params.gender"
                placeholder="请选择性别"
                style="width: 10rem"
                clearable
              >
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>

            <el-form-item label="状态">
              <el-select
                v-model="params.locked"
                placeholder="请选择状态"
                style="width: 10rem"
                clearable
              >
                <el-option label="正常" :value="0" />
                <el-option label="锁定" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch" :icon="Search"
                >搜索</el-button
              >
              <el-button type="default" @click="onReset" :icon="RefreshRight"
                >重置</el-button
              >
            </el-form-item>
          </el-form>

          <el-button type="primary" :icon="Plus" @click="open(null)"
            >新增</el-button
          >
          <el-button type="danger" :icon="Delete" @click="onDelete(null)"
            >批量删除</el-button
          >
        </div>
      </template>
      <template #operate="{ row }">
        <el-button type="warning" link :icon="Unlock" @click="onLocked(row)">{{
          row.locked === 0 ? '锁定' : '解锁'
        }}</el-button>
        <el-button type="primary" link :icon="Edit" @click="open(row.id)"
          >编辑</el-button
        >
        <el-button type="danger" link :icon="Delete" @click="onDelete(row.id)"
          >删除</el-button
        >
      </template>

      <template #pagination>
        <el-pagination
          background
          layout="sizes,prev, pager, next,total"
          :total="total"
          :page-sizes="[10, 15, 20]"
          v-model:page-size="params.pageSize"
          v-model:current-page="params.pageNo"
          @current-change="currentChange"
          @size-change="sizeChange"
        />
      </template>
    </TabComponent>

    <!-- 弹层 -->
    <div>
      <el-dialog
        v-model="dialogVisible"
        :title="formData.id ? '修改信息' : '新增员工'"
        width="500"
      >
        <div class="form-box">
          <el-form
            ref="formRef"
            style="max-width: 18rem"
            :model="formData"
            :rules="formRules"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="formData.username"
                :disabled="formData.id ? true : false"
              />
            </el-form-item>
            <el-form-item label="昵称：" prop="nickName">
              <el-input v-model="formData.nickName" autocomplete="off" />
            </el-form-item>
            <el-form-item v-if="!formData.id" label="密码：" prop="password">
              <el-input v-model="formData.password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="手机号码：" prop="phone">
              <el-input v-model="formData.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="性别：" prop="gender">
              <el-radio-group v-model="formData.gender" @change="selectGender">
                <el-radio :value="1" size="large">男</el-radio>
                <el-radio :value="2" size="large">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="onSubmit">
              {{ formData.id ? '修改' : '新增' }}
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.page {
  .search-box {
    padding-top: 0.5rem;
  }

  .table-box {
    .operate-box {
      margin: 1rem 0;
    }
  }

  .page-box {
    margin-top: 1.25rem;
    display: flex;
    justify-content: end;
  }
}
</style>
